import axios from 'axios';
import type { AxiosInstance } from 'axios';
import type { HYRequestInterceptors, HYRequestConfig } from './type';

import { ElLoading } from 'element-plus';
import { ILoadingInstance } from 'element-plus/lib/el-loading/src/loading.type';

// 类具有更强的封装性
class HYRequest {
  instance: AxiosInstance;
  interceptors?: HYRequestInterceptors;
  showLoading: boolean;
  loading?: ILoadingInstance;

  // 将AxiosRequestConfig类型换成HYRequestConfig
  constructor(config: HYRequestConfig) {
    this.instance = axios.create(config);
    // 当没有传的时候,默认是true
    this.showLoading = config.showLoading ?? true;
    this.interceptors = config.interceptors;

    // 从config中取出的拦截器是对应的实例的拦截器
    this.instance.interceptors.request.use(
      this.interceptors?.requestInterceptor,
      this.interceptors?.requestInterceptorCatch
    );

    this.instance.interceptors.response.use(
      this.interceptors?.responseInterceptor,
      this.interceptors?.responseInterceptorCatch
    );

    // 添加所有实例都有的拦截器
    this.instance.interceptors.request.use(
      (config) => {
        console.log('全局请求success');

        if (this.showLoading) {
          // 添加loading效果
          this.loading = ElLoading.service({
            lock: true,
            text: '正在请求数据...'
          });
        }

        return config;
      },
      (err) => {
        console.log('全局请求failed');
        return err;
      }
    );

    this.instance.interceptors.response.use(
      (res) => {
        console.log('全局响应success');

        // 将loading移除
        setTimeout(() => {
          this.loading?.close();
        }, 3000);

        const data = res.data;
        if (data.returnCode === '-1001') {
          console.log('请求失败~, 错误信息');
        } else {
          return data;
        }
      },
      (err) => {
        console.log('全局响应failed');
        // 例子：判断不同的HttpErrorCode显示不同的错误信息
        if (err.response.status === 404) {
          console.log('404的错误~');
        }
        return err;
      }
    );
  }

  request<T>(config: HYRequestConfig): Promise<T> {
    return new Promise((resolve, reject) => {
      if (config.interceptors?.requestInterceptor) {
        config = config.interceptors.requestInterceptor(config);
      }

      if (config.showLoading === false) {
        this.showLoading = config.showLoading;
      }

      this.instance
        .request<any, T>(config)
        .then((res) => {
          // 1.单个请求对数据的处理
          if (config.interceptors?.responseInterceptor) {
            res = config.interceptors.responseInterceptor(res);
          }
          // 2.重新设置为true,这样不会影响下次请求
          this.showLoading = true;
          // 3.将结果resolve返回出去
          resolve(res);
        })
        .catch((err) => {
          this.showLoading = true;
          reject(err);
          return err;
        });
    });
  }

  get<T>(config: HYRequestConfig): Promise<T> {
    return this.request<T>({ ...config, method: 'GET' });
  }

  post<T>(config: HYRequestConfig): Promise<T> {
    return this.request<T>({ ...config, method: 'POST' });
  }

  delete<T>(config: HYRequestConfig): Promise<T> {
    return this.request<T>({ ...config, method: 'DELETE' });
  }

  patch<T>(config: HYRequestConfig): Promise<T> {
    return this.request<T>({ ...config, method: 'PATCH' });
  }
}

export default HYRequest;
